package service

import (
	"context"
	"errors"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"user_srv/basic/config"
	__ "user_srv/basic/userproto"
	"user_srv/handler/dao"
	"user_srv/pkg"
	"user_srv/untils"
)

// SendSms 发送短信验证码
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	if !pkg.IsValidMobile(in.Mobile) {
		return nil, errors.New("手机号格式错误")
	}
	// 检查短信发送次数是否超过限制
	keyErr := "SmsErr" + in.Mobile
	count, _ := config.Rdb.Get(config.Ctx, keyErr).Int()
	if count > 0 {
		return nil, errors.New("短信发送次数超过限制，请稍后再试")
	}
	code := rand.Intn(9000) + 1000
	sms := untils.HuYiWuXian{}
	response := sms.SendSms(in.Mobile, strconv.Itoa(code))
	// 解析响应
	if response.StatusCode != http.StatusOK {
		return nil, errors.New("发送短信失败")
	}
	key := "sms" + in.Mobile
	// 短信发送成功后，将验证码存储到Redis中，过期时间为1分钟
	config.Rdb.Set(config.Ctx, key, code, time.Minute)
	// 短信发送成功后，增加发送次数
	config.Rdb.Incr(config.Ctx, keyErr)
	// 短信发送成功后，设置过期时间为1分钟
	config.Rdb.Expire(config.Ctx, keyErr, time.Minute)

	return &__.SendSmsResp{
		Msg: "短信发送成功",
	}, nil
}

// SmsLogin 用户短信登录
func (s *Server) SmsLogin(_ context.Context, in *__.SmsLoginReq) (*__.SmsLoginResp, error) {
	err, u := dao.UserLogin(in)
	if err != nil {
		return nil, err
	}
	return &__.SmsLoginResp{
		Id: int64(u.Id),
	}, nil
}

// UserProfile 用户个人信息
func (s *Server) UserProfile(_ context.Context, in *__.UserProfileReq) (*__.UserProfileResp, error) {
	err, id := dao.UserProfile(in)
	if err != nil {
		return nil, err
	}
	return &__.UserProfileResp{Id: int64(id)}, nil
}

// PasswordLogin 用户密码登录
func (s *Server) PasswordLogin(_ context.Context, in *__.PasswordLoginReq) (*__.PasswordLoginResp, error) {
	err, u := dao.PasswordLogin(in)
	if err != nil {
		return nil, errors.New(err.Error())
	}
	return &__.PasswordLoginResp{Id: int64(u)}, nil
}
func (s *Server) GetUserProfileList(_ context.Context, in *__.GetUserProfileReq) (*__.GetUserProfileResp, error) {
	err, list := dao.GetUserInfoList(in)
	if err != nil {
		return nil, errors.New(err.Error())
	}
	return &__.GetUserProfileResp{
		List: list,
	}, nil
}

// GetUserDetail 获取用户详情
func (s *Server) GetUserDetail(_ context.Context, in *__.GetUserDetailReq) (*__.GetUserDetailResp, error) {
	err, u := dao.GetUserDetail(in)
	if err != nil {
		return nil, err
	}
	return &__.GetUserDetailResp{
		Id:                       int32(u.Id),
		Mobile:                   u.Mobile,
		NickName:                 u.NickName,
		RealName:                 u.RealName,
		IdCard:                   u.IdCard,
		Sex:                      int64(u.Sex),
		Address:                  u.Address,
		IdCardVerificationStatus: int64(u.IdCardVerificationStatus),
		Signature:                u.Signature,
		Status:                   int64(u.Status),
	}, nil
}
